import 'dart:async';
import 'dart:io';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index_nav/index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/index_nav_page/smart_home_index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/show_progress_notifier.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_3d_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_show_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_single_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_select_column_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_select_image_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_select_type_to_publish_widget.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_pages_widget_new.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/video_upload_service.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_and_terminal_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_list_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_info_page.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_store_name_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_style_image_event.dart';
import 'package:e_reception_flutter/ui/smart_home/handle_smart_home_image_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_more_operations_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_select_style_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_dialog_widget/general_animation_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'
as extended;
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../app_main.dart';
import '../../change_main_page_event.dart';
import '../smart_home_style_type_bean.dart';
import '../smart_home_upload_service.dart';
import 'custom_tab_indicator.dart';
import 'handle_smart_home_image_by_column_page.dart';

/// 品牌或门店详情
class SmartHomeStoreDetailsPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeStoreDetailsPage";
  //品牌或门店id
  final String id;
  final String brandName;
  final String storeName;
  final String logo;

  const SmartHomeStoreDetailsPage(
      {Key key, this.id, this.brandName, this.storeName, this.logo}) : super(key:key);

  @override
  _SmartHomeStoreDetailsPageState createState() => _SmartHomeStoreDetailsPageState();

  static Future<dynamic> navigatorPush(BuildContext context, String id,
      String brandName, String storeName, String logo){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeStoreDetailsPage(
          id: id,
          brandName: brandName,
          storeName: storeName,
          logo: logo,
        ),
        routeName: SmartHomeStoreDetailsPage.ROUTER
    );
  }
}

class SmartHomeGroupBean{
  String groupName;
  String count;

  SmartHomeGroupBean(this.groupName, this.count);

}

class _SmartHomeStoreDetailsPageState extends BasePagerState<SmartHomeStoreDetailListItemBean, SmartHomeStoreDetailsPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin{

  SmartHomePublishViewModel _viewModel;
  SmartHomeStoreDetailViewModel _detailViewModel;
  TabController _tabController;
  List<ColumnListBean> _tabsList;
  StreamSubscription _columnUpdateStreamSubscription;
  StreamSubscription _nameUpdateStreamSubscription;

  //选中的style,空代表全部
  List<String> _selectStyleList;
  List<SmartHomeStyleTypeBean> _styleList;
  //上传选中的第一个分类id
  String _selectScid;
  //选中的分类
  ColumnListBean _columnType = null;
  int _userCnt = 0;
  int _totalPicCnt = 0;
  String _title;
  String _samplePush;
  String _brandName;
  String _storeName;
  String _logo;
  ColumnDataBean _mDataBean;
  GlobalKey _globalKey = new GlobalKey();
  double _offSet = 0;

  GlobalKey _uploadGlobalKey = new GlobalKey();
  double _uploadOffSet = 0;
  String _stids = "";
  String stnames = "";
  String _cacheKey;
  VideoUploadService _videoUploadService;

  VideoPlayerController _videoController;
  @override
  void initState() {
    //监听Widget是否绘制完毕
    super.initState();
    _brandName = widget?.brandName??"";
    _storeName = widget?.storeName??"";

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getRenderBox();
      _getUploadRenderBox();
      _videoUploadService = VideoUploadService.getInstance();
    });
    _title = "$_brandName（$_storeName）";
    _logo = widget?.logo??"";
    _selectStyleList = new List();

    _viewModel = new SmartHomePublishViewModel(this);
    _detailViewModel = new SmartHomeStoreDetailViewModel(this);
    _viewModel.getColumnList(context, widget?.id, _getStyles(), _stids, stnames);
    _detailViewModel.recordSmartHomeLastVisit(widget?.id);
    _tabsList =  new List();
    // _tabController = TabController(initialIndex:0, length: _tabsList?.length ?? 0, vsync: this);
    // _tabController.addListener(() {
    //   if(!(_tabController?.indexIsChanging??false)){
    //     setState(() {
    //       _columnType = _tabsList?.elementAt(_tabController.index);
    //     });
    //   }
    // });
    _cacheKey = NetApi.SMART_HOME_GET_COLUMN_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + widget?.id;
    _columnUpdateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeCategoryEvent>()?.listen((event) {
          if(StringUtils.isNotEmpty(event.id??"")){
            _selectScid = event.id??"";
          }
          _viewModel?.getColumnOnLine(widget?.id, _getStyles(), _stids, stnames, _cacheKey, null);
          _tabController?.animateTo(0);
        });


    _nameUpdateStreamSubscription =
        VgEventBus.global.on<RefreshStoreNameEvent>()?.listen((event) {
          bool needSetState = false;
          if(StringUtils.isNotEmpty(event?.brandName) && _brandName != event.brandName){
            _brandName = event?.brandName;
            needSetState = true;
          }
          if(StringUtils.isNotEmpty(event?.storeName) && _storeName != event.storeName){
            _storeName = event?.storeName;
            needSetState = true;
          }
          _title = "$_brandName（$_storeName）";
          if(event?.logo != null && _logo != event.logo){
            _logo = event.logo;
            needSetState = true;
          }
          if(needSetState){
            setState(() {
            });
          }
        });

  }

  _getRenderBox(){
    RenderBox renderBox = _globalKey?.currentContext?.findRenderObject();
    if(renderBox == null){
      return;
    }
    print("renderBox ${renderBox.localToGlobal(Offset(0,0))})");
    _offSet = renderBox.localToGlobal(Offset(0,0)).dy;
  }
  _getUploadRenderBox(){
    RenderBox renderBox = _uploadGlobalKey?.currentContext?.findRenderObject();
    if(renderBox == null){
      return;
    }
    print("renderBox ${renderBox.localToGlobal(Offset(0,0))})");
    _uploadOffSet = renderBox.localToGlobal(Offset(0,0)).dy;
  }


  @override
  void dispose() {
    _columnUpdateStreamSubscription?.cancel();
    _nameUpdateStreamSubscription?.cancel();
    _videoController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        if(StateHelper.has<IndexNavPage>() || StateHelper.has<SmartHomeIndexNavPage>()){
          return true;
        }else{
          //没有任何的主页，说明是直接进的，这个时候返回到首页，并且选中智能家居展示页面
          RouterUtils.pop(context);
          VgEventBus.global.send(new ChangeMainPageEvent(SmartHomeIndexNavPage.ROUTER));
          return true;
        }
      },
      child: LightAnnotatedRegion(
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            resizeToAvoidBottomPadding: false,
            backgroundColor: Color(0xFFF6F7F9),
            body: _toPlaceHolderWidget(),
          )
      ),
    );
    // return LightAnnotatedRegion(
    //     child: Scaffold(
    //       resizeToAvoidBottomInset: false,
    //       resizeToAvoidBottomPadding: false,
    //       backgroundColor: Color(0xFFF6F7F9),
    //       body: _toPlaceHolderWidget(),
    //     )
    // );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
            errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
            errorOnClick: () => _viewModel
                .getColumnList(context, widget?.id, _getStyles(), _stids, stnames),
            loadingOnClick: () => _viewModel
                .getColumnList(context, widget?.id, _getStyles(), _stids, stnames),
            child: child,
          );
        },
        child: _toMainColumnWidget());
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toCustomScrollWidget(){
    return CustomScrollView(
      slivers: [
        SliverPersistentHeader(
          floating: true,
          pinned: true,
          delegate: SliverCustomHeaderDelegate(
              collapsedHeight: 44,
              expandedHeight: 62,
              paddingTop: 27.0,
              bg: _toExpandedTopBarWidget(),
              title: _toTopBarWidget()
          ),
        ),
        SliverToBoxAdapter(
          child: _toStaggeredWidget(),
        ),
      ],
    );
  }

  Widget _toScrollWidget(){
    return extended.NestedScrollView(
      physics: BouncingScrollPhysics(),
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
        return[
          SliverAppBar(
            pinned: true,
            floating: false,
            snap: false,
            expandedHeight: 62 + ScreenUtils.getStatusBarH(context),
            backgroundColor: Colors.white,
            shadowColor: Colors.white,
            centerTitle: false,
            leading: Container(),
            title: Container(),
            elevation: 0,
            flexibleSpace: FlexibleSpaceBar(
              background: _toExpandedTopBarWidget(),
              title: _toTopBarWidget(),
            ),
            actions: [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: (){
                  RouterUtils.pop(context);
                },
                child: Container(
                  alignment: Alignment.topCenter,
                  padding: EdgeInsets.only(top:15, left:15, right: 15),
                  child: Image.asset(
                    "images/icon_close_volume_dialog.png",
                    width: 15,
                    height: 15,
                  ),
                ),
              )
            ],
          ),
          SliverPersistentHeader(
            pinned: true,
            key: UniqueKey(),
            delegate: CommonSliverPersistentHeaderDelegate(
                maxHeight: 90,
                minHeight: 90,
                child: Column(
                  children: [
                    _toCategoryWidget(),
                    _toStyleWidget(),
                  ],
                )
            ),
          ),
        ];
      },
      body:                 _toStaggeredWidget(),
    );
  }

  Widget _toExpandedTopBarWidget(){
    return Container(
      height: 62 + ScreenUtils.getStatusBarH(context),
      color: Colors.white,
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(top: ScreenUtils.getStatusBarH(context)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 15,),
          // GestureDetector(
          //   behavior: HitTestBehavior.opaque,
          //   onTap: (){
          //     SmartHomeInfoPage.navigatorPush(context, widget?.id, SmartHomeStoreDetailsPage.ROUTER);
          //   },
          //   child: ClipRRect(
          //     borderRadius: BorderRadius.circular(8),
          //     child: Container(
          //       width: 40,
          //       height: 40,
          //       child: VgCacheNetWorkImage(
          //         _logo,
          //         imageQualityType: ImageQualityType.middleUp,
          //         fit: BoxFit.contain,
          //         errorWidget:
          //         Image.asset("images/icon_logo_empty.png"),
          //         placeWidget:
          //         Image.asset("images/icon_logo_empty.png"),
          //       ),
          //     ),
          //   ),
          // ),
          // SizedBox(width: 10,),
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                SmartHomeInfoPage.navigatorPush(context, widget?.id, SmartHomeStoreDetailsPage.ROUTER);
              },
              child: Container(
                height: 62,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(bottom: 4),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Container(
                          constraints: BoxConstraints(
                            maxWidth: ScreenUtils.screenW(context) - 15 - 6 - 6 - 60,
                          ),
                          child: Text(
                            _title,
                            softWrap: true,
                            style: TextStyle(
                              fontSize: 17,
                              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                              fontWeight: FontWeight.w600,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        SizedBox(width: 6,),
                        Expanded(
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(
                                "images/icon_arrow_right_grey.png",
                                width: 6,
                                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                              ),
                            ],
                          ),
                        ),
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: (){
                            if(StateHelper.has<IndexNavPage>() || StateHelper.has<SmartHomeStoreListPage>()){
                              RouterUtils.pop(context);
                            }else{
                              RouterUtils.pop(context);
                              VgEventBus.global.send(new ChangeMainPageEvent(SmartHomeIndexNavPage.ROUTER));
                            }
                          },
                          child: Container(
                            padding: EdgeInsets.only(left:30, right: 15),
                            height: 30,
                            alignment: Alignment.center,
                            child: Image.asset(
                              "images/icon_close_volume_dialog.png",
                              width: 15,
                              height: 15,
                            ),
                          ),
                        )
                      ],
                    ),
                    SizedBox(height: 1,),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        // SmartHomeSelectTerminalPage.navigatorPush(context, widget?.id, _totalPicCnt);
                        SmartHomeStoreAndTerminalPage.navigatorPush(context, widget?.id);
                      },
                      child: Row(
                        children: [
                          Text(
                            "终端显示屏 ",
                            style: TextStyle(
                              fontSize: 11,
                              color: Color(0XFF5E687C),
                            ),
                          ),
                          Text(
                            ((_userCnt??0)>0)?"${_userCnt??"0"}":"0",
                            style: TextStyle(
                              fontSize: 11,
                              color: ((_userCnt??0)>0)?Color(0XFF00C6C4):Color(0XFFF95355),
                            ),
                          ),
                        ],
                      ),
                    ),
                    // Row(
                    //   children: [
                    //
                    //     Container(
                    //       margin: EdgeInsets.symmetric(horizontal: 8),
                    //       width: 1,
                    //       height: 11,
                    //       color: Color(0XFF888888),
                    //     ),
                    //     GestureDetector(
                    //       behavior: HitTestBehavior.opaque,
                    //       onTap: (){
                    //         SmartHomeWaterListPage.navigatorPush(context, _mDataBean?.comSmarthome);
                    //       },
                    //       child: Row(
                    //         children: [
                    //           Text(
                    //             "文件水印 ",
                    //             style: TextStyle(
                    //               fontSize: 11,
                    //               color: Color(0XFF5E687C),
                    //             ),
                    //           ),
                    //           Text(
                    //             (_mDataBean?.comSmarthome?.isWaterOpen()??false)?"启用":"关闭",
                    //             style: TextStyle(
                    //               fontSize: 11,
                    //               color: (_mDataBean?.comSmarthome?.isWaterOpen()??false)?Color(0XFF00C6C4):Color(0XFFF95355),
                    //             ),
                    //           ),
                    //         ],
                    //       ),
                    //     ),
                    //   ],
                    // )
                  ],
                ),
              ),
            ),
          ),

        ],
      ),
    );
  }

  Widget _toMainColumnWidget() {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.columnValueNotifier,
      builder: (BuildContext context, ColumnDataBean columnDataBean, Widget child){
        if(columnDataBean != null && columnDataBean.columnList != null){
          if(columnDataBean.toString() != (_mDataBean?.toString()??"")){
            _tabsList.clear();
            _tabsList.addAll(columnDataBean.columnList);
            int initIndex = getInitIndex();
            _columnType = _tabsList?.elementAt(initIndex);
            _tabController = TabController(initialIndex:0, length: _tabsList?.length ?? 0, vsync: this,);
            _tabController.addListener(() {
              if(!(_tabController?.indexIsChanging??false)){
                setState(() {
                  _columnType = _tabsList?.elementAt(_tabController.index);
                });
              }
            });
            _tabController.index = initIndex;
            _tabController.animateTo(initIndex);
            print("initIndex:" + initIndex.toString() + ",_selectScid:" + (_selectScid??""));

            // Future.delayed(Duration(milliseconds: 1000),(){
            //   _tabController.animateTo(initIndex);
            //   // setState(() {
            //   //   _columnType = _tabsList?.elementAt(_tabController.index);
            //   // });
            // });
          }
          if(columnDataBean != null && columnDataBean.terCnt != null){
            _userCnt = columnDataBean.terCnt;
          }
          if(columnDataBean != null && columnDataBean.getPicTotalCnt() != null){
            _totalPicCnt = columnDataBean.getPicTotalCnt();
          }
          _mDataBean = columnDataBean;
          _brandName = columnDataBean?.comSmarthome?.brand??"";
          _storeName = columnDataBean?.comSmarthome?.name??"";
          _title = "$_brandName（$_storeName）";
          _logo = columnDataBean?.comSmarthome?.logo??"";
          _samplePush = columnDataBean?.comSmarthome?.samplePush;
        }

        return Stack(
          children: [
            Column(
              children: [
                // _toTopBarWidget(),
                _toExpandedTopBarWidget(),
                _toCategoryWidget(),
                _toStyleWidget(),
                _toUploadView(),
                _toStaggeredWidget(),
              ],
            ),
            // _toScrollWidget(),
            _toUploadWidget(),
          ],
        );
      },
    );
  }

  ///页面标题
  Widget _toTopBarWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(top: ScreenUtils.getStatusBarH(context)),
      child: Container(
        height: 44,
        child: Row(
          children: [
            ClickAnimateWidget(
              child: Container(
                width: 40,
                height: 44,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 15.6),
                child: Image.asset(
                  "images/top_bar_back_ico.png",
                  width: 9,
                  color: Color(0xFF5E687C),
                ),
              ),
              scale: 1.4,
              onClick: () {
                RouterUtils.pop(context);
              },
            ),
            Text(
              _title,
              style: TextStyle(
                  fontSize: 17,
                  fontWeight: FontWeight.w600,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C()
              ),
            ),
            Spacer(),
            // _toMoreOperationWidget(),
          ],
        ),
      ),
    );
  }


  ///更多操作
  Widget _toMoreOperationWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SmartHomeMoreOperationsDialog.navigatorPushDialog(context,
            _title,
            _userCnt,
                (){
              _onEdit();
            },
                (){
              _onSetTerminal();
            }
        );
      },
      child: Container(
        height: 44,
        width: 50,
        child: Stack(
          children: [
            Center(
              child: Image.asset(
                "images/icon_more_horizontal.png",
                width: 20,
              ),
            ),
            Align(
              alignment: Alignment.topRight,
              child: Container(
                margin: EdgeInsets.only(left: 0, right: 7, top: 8),
                width: 8,
                height: 8,
                decoration: BoxDecoration(
                    color: (_userCnt>0)?Color(0xFF00C6C4):ThemeRepository.getInstance()
                        .getMinorRedColor_F95355(),
                    shape: BoxShape.circle),
              ),
            ),
          ],
        ),
      ),
    );
  }


  ///编辑
  _onEdit(){
    RouterUtils.pop(context);
    SmartHomeInfoPage.navigatorPush(context, widget?.id, SmartHomeStoreDetailsPage.ROUTER);
  }

  ///播放设备
  _onSetTerminal(){
    RouterUtils.pop(context);
    // SmartHomeSelectTerminalPage.navigatorPush(context, widget?.id, _totalPicCnt);
    SmartHomeStoreAndTerminalPage.navigatorPush(context, widget?.id);
  }

  ///分类栏
  Widget _toCategoryWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Theme(
                data: ThemeData(
                    highlightColor: Colors.transparent,
                    splashColor: Colors.transparent),
                child: _toTabBarWidget()),
          ),
          _toSelectCategoryWidget(),
        ],
      ),
    );
  }

  ///跳转到第一个有数据的
  int getInitIndex(){
    int index = 0;
    // if(StringUtils.isNotEmpty(_selectScid)){
    //   for(int i = 0; i < _tabsList?.length; i++){
    //     if(_tabsList[i].scid  == _selectScid){
    //       index = i;
    //       _columnType = _tabsList[i];
    //     }
    //   }
    //
    // }else{
    //   if(_columnType == null || (_columnType?.cnt??0) == 0){
    //     for(int i = 0; i < _tabsList?.length; i++){
    //       if(_tabsList[i].cnt > 0){
    //         index = i;
    //         break;
    //       }
    //     }
    //     return index;
    //   }
    //   for(int i = 0; i < _tabsList?.length; i++){
    //     if(_tabsList[i].scid == _columnType?.scid){
    //       index = i;
    //     }
    //   }
    // }
    // print("index:" + index.toString());
    return index;
  }

  int getIndex(){
    int index = 0;
    for(int i = 0; i < _tabsList?.length; i++){
      if(_tabsList[i].scid == _columnType?.scid){
        index = i;
      }
    }
    return index;
  }

  ///选择分类按钮
  Widget _toSelectCategoryWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        SmartHomeSelectColumnDialog.navigatorPushDialog(context, _columnType, _tabsList, widget?.id, (selectType) {
          setState(() {
            _columnType = selectType;
            _tabController.animateTo(getIndex());
          });
        });
      },
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.only(top: 3),
        height: 50,
        width: 43,
        child: Image.asset("images/icon_smart_home_category.png",
          width: 13,
        ),
      ),
    );
  }

  ///分类bar
  Widget _toTabBarWidget() {
    return TabBar(
      controller: _tabController,
      onTap: (index){
        _columnType = _tabsList?.elementAt(index);
      },
      isScrollable: true,
      indicatorSize: TabBarIndicatorSize.label,
      unselectedLabelStyle: TextStyle(
          color: Color(0xFF8B93A5),
          fontSize: 15,
          height: 1.2),
      labelStyle: TextStyle(
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          fontSize: 15,
          fontWeight: FontWeight.w600,
          height: 1.2),
      labelPadding: EdgeInsets.only(left: 20, right: 0, bottom: 5),
      labelColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      unselectedLabelColor: Color(0xFF8B93A5),
      indicatorColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      indicatorPadding: EdgeInsets.only(left: 10, right: 27),
      indicator: CustomTabIndicator(),
      tabs: List.generate(_tabsList?.length ?? 0, (index) {
        return Container(
          padding: EdgeInsets.only(top: 10),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(
                _tabsList?.elementAt(index)?.name ?? "",
              ),
              SizedBox(
                width: 3,
              ),
              Container(
                margin: EdgeInsets.only(top: 3),
                child: Text(
                  "${_tabsList?.elementAt(index)?.cnt ?? 0}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 12,
                  ),
                ),
              )
            ],
          ),
        );
      }),
    );
  }

  void _setStyle(){
    if(_styleList == null){
      _viewModel.getLatestStyle(widget?.id, (styleList){
        _styleList = new List();
        _styleList.addAll(styleList);
        SmartHomeSelectStyleDialog.navigatorPushDialog(context, _styleList, _selectStyleList, _offSet, (selectStyleList) {
          setState(() {
            _selectStyleList = selectStyleList;
          });
          _viewModel?.getColumnOnLine(widget?.id, _getStyles(), _stids, stnames, _cacheKey, null);
          VgEventBus.global.send(new RefreshStyleImageEvent(_getStyles()));
        });
      });
    }else{
      SmartHomeSelectStyleDialog.navigatorPushDialog(context, _styleList, _selectStyleList, _offSet, (selectStyleList) {
        setState(() {
          _selectStyleList = selectStyleList;
        });
        _viewModel?.getColumnOnLine(widget?.id, _getStyles(), _stids, stnames, _cacheKey, null);
        VgEventBus.global.send(new RefreshStyleImageEvent(_getStyles()));
      });
    }
  }

  ///风格筛选
  Widget _toStyleWidget(){
    // _getRenderBox();
    return Container(
      height: 44,
      key: _globalKey,
      padding: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Visibility(
            visible: true,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                _getRenderBox();
                _setStyle();
              },
              child: Row(
                children: [
                  Image.asset(
                    "images/icon_select_style.png",
                    width: 16,
                  ),
                  SizedBox(width: 4,),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "全部风格",
                        style: TextStyle(
                            color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                            fontSize: 12
                        ),
                      ),
                      Visibility(
                        visible: _selectStyleList?.isNotEmpty,
                        child: Text(
                          "/",
                          style: TextStyle(
                              color: Color(0xFF1890FF),
                              fontSize: 12
                          ),
                        ),
                      ),
                      Visibility(
                        visible: _selectStyleList?.isNotEmpty,
                        child: Text(
                          "${_selectStyleList?.length??""}",
                          style: TextStyle(
                              color: Color(0xFF1890FF),
                              fontSize: 12
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Spacer(),
          Visibility(
            visible: false,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                if(!(_tabController?.animation?.isCompleted??false)){
                  loading(true);
                  Future.delayed(Duration(milliseconds: 1000),(){
                    loading(false);
                    HandleSmartHomeImageByColumnPage.navigatorPush(context, (_columnType == null)?_tabsList[0]?.scid:_columnType?.scid, widget?.id);
                  });
                }else{
                  HandleSmartHomeImageByColumnPage.navigatorPush(context, (_columnType == null)?_tabsList[0]?.scid:_columnType?.scid, widget?.id);
                }

              },
              child: Container(
                padding: const EdgeInsets.only(left: 10,right: 10),
                height: 24,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(12),
                  border:  Border.all(
                      color: Color(0xFFB0B3BF),
                      width: 0.5),
                ),
                child: Text(
                  "选择",
                  style: TextStyle(
                      color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                      fontSize: 12,
                      height: 1.2
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _getStyles(){
    String styles = "";
    _selectStyleList.forEach((element) {
      styles += element;
      styles += ",";
    });
    if(StringUtils.isNotEmpty(styles)){
      styles = styles.substring(0, styles.length-1);
    }
    print("styles:" + styles);
    return styles;
  }


  ///上传布局
  Widget _toUploadView(){
    return StreamBuilder<List<SmartHomeUploadItemBean>>(
        stream: _videoUploadService?.uploadServiceStream?.stream,
        initialData: _videoUploadService?.getUploadingInfoList(widget?.id),
        builder: (context, AsyncSnapshot<List<SmartHomeUploadItemBean>> snapshot) {
          List<SmartHomeUploadItemBean> infoList = snapshot?.data;
          if(infoList == null || infoList.isEmpty){
            return Container();
          }else{
            SmartHomeUploadItemBean firstItem = infoList.first;
            double padding = (infoList.length > 1)?12:15;
            return Container(
                padding: EdgeInsets.only(left: 12, right: 12, top: padding, bottom: padding),
                color: Colors.white,
                child: Column(children: <Widget>[
                  Row(
                    children: <Widget>[
                      _toCoverWidget(infoList),
                      SizedBox(
                        width: 5,
                      ),
                      Text("正在上传视频",
                          style: TextStyle(color: Color(0xFF999999), fontSize: 13)),
                      Spacer(),
                      GestureDetector(
                        child: Container(
                          padding: const EdgeInsets.only(left: 10,right: 10),
                          height: 24,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Color(0xFF999999), width: 0.5),
                          ),
                          child: Text(
                            "终止",
                            style: TextStyle(
                              fontSize: 13,
                              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                            ),
                          ),
                        ),
                        onTap: () async{
                          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(
                            context,
                            title: "提示",
                            content: "确定终止上传视频？",
                            cancelText: "取消",
                            confirmText: "确定",
                            confirmBgColor:
                            ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                            cancelBgColor: Color(0xFFF6F7F9),
                            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                            widgetBgColor: Colors.white,
                          );
                          if (result ?? false) {
                            if(infoList.length > 1){
                              _videoUploadService?.cancelAll(firstItem?.id);
                            }else{
                              _videoUploadService?.cancelUpload(firstItem?.id, firstItem?.localUrl,);
                            }
                          }
                          // _viewModel.uploadModel!.removeCurrentBean();
                        },
                      )
                    ],
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Container(
                    height: 2,
                    child: StreamBuilder<SmartHomeUploadItemBean>(
                      stream: _videoUploadService?.uploadingStreamMap[firstItem?.id]?.stream,
                      initialData: _videoUploadService?.getCurrentUploadingInfo(widget?.id, firstItem?.id),
                      builder: (context, AsyncSnapshot<SmartHomeUploadItemBean> snapshot){
                        SmartHomeUploadItemBean item = snapshot?.data;
                        return LinearProgressIndicator(
                            value: (item?.progress ?? 0)/100.0,
                            backgroundColor: Color(0x331797CE),
                            valueColor:
                            new AlwaysStoppedAnimation<Color>(Color(0xFF179ECE)));
                      },

                    ),
                  ),
                ]));
          }
        }
    );
  }

  ///根据上传视频的数据获取封面布局
  Widget _toCoverWidget(List<SmartHomeUploadItemBean> infoList){
    if(infoList.length == 1){
      SmartHomeUploadItemBean item = infoList.elementAt(0);
      return Container(
        width: 30,
        height: 30,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: <Widget>[
            item?.videoLocalCover != null
                ? Image.file(
              File(item?.videoLocalCover??""),
              width: 30,
              height: 30,
              cacheWidth: 30,
              cacheHeight: 30,
              fit: BoxFit.cover,
            )
                : Container(
              width: 30,
              height: 30,
            ),
            Image.asset(
              "images/icon_smart_home_video_play.png",
              width: 10,
              height: 10,
            )
          ],
        ),
      );
    }else{
      SmartHomeUploadItemBean firstItem = infoList.elementAt(0);
      SmartHomeUploadItemBean secondItem = infoList.elementAt(1);
      return Stack(
        children: [
          Container(
            width: 30,
            height: 30,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: <Widget>[
                secondItem?.videoLocalCover != null
                    ? Image.file(
                  File(secondItem?.videoLocalCover??""),
                  width: 30,
                  height: 30,
                  cacheWidth: 30,
                  cacheHeight: 30,
                  fit: BoxFit.cover,
                )
                    : Container(
                  width: 30,
                  height: 30,
                ),
                Image.asset(
                  "images/icon_smart_home_video_play.png",
                  width: 10,
                  height: 10,
                )
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 6, top: 6),
            child: Container(
              width: 30,
              height: 30,
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: <Widget>[
                  firstItem?.videoLocalCover != null
                      ? Image.file(
                    File(firstItem?.videoLocalCover??""),
                    width: 30,
                    height: 30,
                    cacheWidth: 30,
                    cacheHeight: 30,
                    fit: BoxFit.cover,
                  )
                      : Container(
                    width: 30,
                    height: 30,
                  ),
                  Image.asset(
                    "images/icon_smart_home_video_play.png",
                    width: 10,
                    height: 10,
                  )
                ],
              ),
            ),
          ),
        ],
      );
    }
  }



  ///瀑布流
  Widget _toStaggeredWidget(){

    // if((data?.length??0) == 0){
    //   return Expanded(
    //       child: Container(
    //           alignment: Alignment.center,
    //           child: _defaultEmptyCustomWidget("暂无内容")
    //       ));
    // }
    return Expanded(
      child: SmartHomeStoreDetailPagesWidgetNew(
        tabController: _tabController,
        columnList: _tabsList,
        shid: widget?.id,
        title: _title,
        samplePush: _samplePush,
        styles: _getStyles(),
        stids: "",
        stnames: "",
      ),
    );

  }

  ///上传文件布局
  Widget _toUploadWidget(){
    double horizontalWidth = 120;
    double itemWidth = (ScreenUtils.screenW(context) - 30)/3;
    return Positioned(
      bottom: 50,
      key: _uploadGlobalKey,
      left: (ScreenUtils.screenW(context) - horizontalWidth)/2,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: throttle(()  async {
          // // _selectImage();
          // SmartHomePublishPage.navigatorPush(context, "01");
          // // SmartHome3DUploadPage.navigatorPush(context,);
          // await Future.delayed(Duration(milliseconds: 2000));
          _getUploadRenderBox();
          showAnimationDialog(
              context: context,
              transitionType: TransitionType.fade,
              barrierColor: Color(0x00000001),
              transitionDuration: Duration(milliseconds: 100),
              builder: (context){
                return SmartHomeSelectTypeToPublishWidget(
                  offset: _uploadOffSet - 40 - 50 + 5,
                  onTapImage: (){
                    _doPublish(context, "01");
                  },
                  onTapVideo: (){
                    _doPublish(context, "02");
                  },
                  onTap3DLink: (){
                    _doPublish(context, "03");
                  },
                );
              }
          );
        }),
        child: Column(
          children: [
            Container(
              width: 120,
              height: 40,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  borderRadius: BorderRadius.circular(24),
                  boxShadow: [
                    BoxShadow(
                        color: Color(0xff000000).withOpacity(0.1),
                        offset: Offset(0, 0),
                        blurRadius: 40
                    )
                  ]
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image(
                    image: AssetImage("images/icon_upload.png"),
                    width: 20,
                    height: 20,
                  ),
                  SizedBox(width: 5,),
                  Text(
                    "发布",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        height: 1.2,
                        fontWeight: FontWeight.w600
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _doPublish(BuildContext context, String type){
    if(type == "03"){
      ColumnListBean selectColumn = _columnType;
      List<ColumnListBean> columnList = new List();

      for(int i = 0; i < _tabsList.length; i++){
        if("-1" != _tabsList.elementAt(i).getScid()){
          columnList.add(_tabsList.elementAt(i));
        }
      }
      //如果是全部，则取全部外得第一个
      if("-1" == selectColumn.getScid()){
        selectColumn = columnList.elementAt(0);
      }
      SmartHome3DUploadPage.navigatorPush(context,widget?.id, "", columnList, selectColumn);
    }else{
      _selectImageOrVideo(type);

    }

  }

  void _toPublishPage(String type, List<SmartHomeUploadItemBean> selectList){
    ColumnListBean selectColumn = _columnType;
    List<ColumnListBean> columnList = new List();

    for(int i = 0; i < _tabsList.length; i++){
      if("-1" != _tabsList.elementAt(i).getScid()){
        columnList.add(_tabsList.elementAt(i));
      }
    }
    //如果是全部，则取全部外得第一个
    if("-1" == selectColumn.getScid()){
      selectColumn = columnList.elementAt(0);
    }


    String router = SmartHomeStoreDetailsPage.ROUTER;
    if(!StateHelper.has<SmartHomeIndexNavPage>() && !StateHelper.has<IndexNavPage>()){
      router = AppMain.ROUTER;
    }
    if(type == "01"){
      if(selectList.length == 1){
        SmartHomePublishImageSingleUploadPage.navigatorPush(context, widget?.id, selectList, router: router);
      }else{
        SmartHomeSelectImagePage.navigatorPush(context, widget?.id, columnList, selectColumn, selectList, router: router);
      }

      // SmartHomePublishImageShowPage.navigatorPush(context, widget?.id,
      //     type, columnList, selectColumn, router: router, currentList: selectList);
    }else{
      SmartHomePublishPage.navigatorPush(context, widget?.id,
          type, columnList, selectColumn, router: router, currentList: selectList,
          videoUploadService: _videoUploadService);
    }
  }



  void _selectImageOrVideo(String type) async {
    List<String> resultList;
    if ("01" == type) {
      //图片
      resultList = await MatisseUtil.selectPhoto(
          context: context,
          maxSize: 35,
          maxAutoFinish: false,
          imageRadioMaxLimit: 3,
          imageRadioMinLimit: 0.3,
          onRequestPermission: (msg)async{
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示",
              content: msg,
              cancelText: "取消",
              confirmText: "去授权",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              cancelBgColor: Color(0xFFF6F7F9),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            if (result ?? false) {
              PermissionUtil.openAppSettings();
            }
          }
      );
    } else if ("02" == type) {
      resultList = await MatisseUtil.selectVideo(
          context: context, maxSize: 1, maxAutoFinish: false,
          videoDurationLimit: 10*60,
          videoDurationMinLimit: 10,
          onRequestPermission: (msg)async{
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示",
              content: msg,
              cancelText: "取消",
              confirmText: "去授权",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              cancelBgColor: Color(0xFFF6F7F9),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            if (result ?? false) {
              PermissionUtil.openAppSettings();
            }
          });
    }
    _doHandleData(resultList);
  }

  void _doHandleData(List<String> resultList) {
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<SmartHomeUploadItemBean> selectList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    //获取选择的图片或者视频
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }
    if (resultList.length == 1 && MatisseUtil.isVideo(localUrl)) {
      //处理视频逻辑
      loading(true, msg: "视频处理中");
      handleVideo(localUrl, selectList);
    } else {
      loading(true, msg: "图片处理中");
      int computeCount = 0;
      resultList.forEach((element) {
        FileImage image = FileImage(File(element));
        image.resolve(new ImageConfiguration()).addListener(
            new ImageStreamListener((ImageInfo info, bool _) async {
              _imageInfoMap[element] = info;
              computeCount++;
              if (computeCount == resultList.length) {
                loading(false);
                resultList.forEach((element) {
                  selectList.add(SmartHomeUploadItemBean(
                    localUrl: element,
                    type: "01",
                    // scid: _columnType?.getScid() ?? "",
                    folderWidth: _imageInfoMap[element].image.width,
                    folderHeight: _imageInfoMap[element].image.height,
                  ));
                });
                _toPublishPage("01", selectList);
              }
            }));
      });
    }
  }

  ///处理视频的逻辑
  void handleVideo(
      String localUrl, List<SmartHomeUploadItemBean> selectList) async {
    //视频
    SmartHomeUploadItemBean item = SmartHomeUploadItemBean(
      localUrl: localUrl,
      type: "02",
      // scid: _columnType?.getScid() ?? "",
      scid: "",
    );
    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    item.videoLocalCover = tmpVideoCover;

    try {
      _videoController = VideoPlayerController.file(file);
      print("_videoController创建完成");
      await _videoController.initialize();
      print("_videoController初始化完成");
      item.videoDuration = _videoController?.value?.duration?.inSeconds;
      item.folderWidth = _videoController?.value?.size?.width?.floor();
      item.folderHeight = _videoController?.value?.size?.height?.floor();
      item.folderStorage = file.lengthSync();
      selectList.add(item);
      _videoController?.dispose();
      loading(false);
      _toPublishPage("02", selectList);
    } catch (e) {
      _videoController?.dispose();
      loading(false);
      print("视频解析异常111:" + e.toString());
      VgToastUtils.toast(context, "视频解析异常");
    }


  }



  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }



  @override
  bool get wantKeepAlive => true;

}

class SliverCustomHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double collapsedHeight;

  ///折叠的高度
  final double expandedHeight;

  ///展开的高度
  final double paddingTop;
  final Widget bg;
  final Widget title;

  SliverCustomHeaderDelegate({
    this.collapsedHeight,
    this.expandedHeight,
    this.paddingTop,
    this.bg,
    this.title,
  });

  Color makeStickyHeaderBgColor(shrinkOffset) {
    final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
        .clamp(0, 255)
        .toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  Color makeStickyHeaderTextColor(shrinkOffset, isIcon) {
    if (shrinkOffset <= 50) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
          .clamp(0, 255)
          .toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      height: this.maxExtent,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          // 背景图
          bg,
          title,
        ],
      ),
    );
  }

  @override
  double get maxExtent => this.expandedHeight;

  @override
  double get minExtent => this.collapsedHeight + this.paddingTop;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
